import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import React, { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { Form, Input, Upload, Button, message, UploadFile } from 'antd';
import { addtrilal } from '@/api1/trial/index'
import { UploadOutlined } from '@ant-design/icons';
import { ArrowLeftOutlined } from '@ant-design/icons';
const { TextArea } = Input;

export const Addtrial = () => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法
  const baseUrl = 'http://192.168.0.69:8001/api/upload/updateFileToOss'
  const [fileList1, setFileList1] = useState<any[]>([]); // 第一个图片文件列表
  // const fileList1: UploadFile<any>[] = []; // 第一个图片文件列表
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string>('');
  // 表单
  const [form] = Form.useForm();
  // 编辑器内容
  const [html, setHtml] = useState('<p>hello</p>');
  // 模拟 ajax 请求，异步设置 html
  // useEffect(() => {
  //   setTimeout(() => {
  //     setHtml('<p>hello world</p>');
  //   }, 1500);
  // }, []);


  const handlePreview = (file: any) => {
    // 处理预览逻辑
    console.log('Preview file:', file);
  };

  const handleChange1 = ({ fileList }: any) => {
    // 处理第一个图片上传逻辑
    setFileList1(fileList); // 更新文件列表状态
    setUploadedImageUrl(fileList[0].response?.url)

    console.log('FileList1----:', fileList);
  };

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: 'http://192.168.0.69:8001/api/upload/updateFileToOss',
        fieldName: 'file',

        customInsert(res: any, insertFn: any) {  // TS 语法
          // customInsert(res, insertFn) {                  // JS 语法
          // res 即服务端的返回结果
          console.log(res,);

          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(res.url,)
        },
        // 其他配置...
      }
    },
  };



  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {

      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 图片上传配置
  const uploadProps = {
    beforeUpload: () => {
      // Custom logic for file validation, if needed
      return true;
    },
    onChange: (info: { file: { status: string; name: any; }; }) => {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  // 提交表单
  const onFinish = (values: any) => {

 console.log(values,'kkkkk');
 

    addtrilal({
      fileName: values.fileName,
      file: uploadedImageUrl,
      title: values.title,
      price: values.price,
      oriPrice: values.oriPrice
    }).then((e: any) => {
      console.log(e, 'tttttttttt');

      if (e.code == 200) {
        message.success('添加成功！');
        history.back();
      }
      else {
        message.success(e.msg);
        message.error('添加成功！');
      }

      //  navigate('/dashboard');
    })
    // Handle form submission logic here
    console.log('Received values:', values, html);
  };

  return (
    <div>
      <Button
        type="primary"
        className="mb-5"
        icon={<ArrowLeftOutlined />}
        onClick={() => {
          // Navigate back to the previous route
          history.back();
        }}
      >
        返回
      </Button>
      <Form form={form} onFinish={onFinish} layout="vertical">
        <Form.Item
          label="标题图片"
          name="image"
          rules={[{ required: true, message: '请输入主标题' }]}
      
        >
          <Upload
            showUploadList={false}
            action={baseUrl}
            listType="picture-card"
            fileList={fileList1}
            onPreview={handlePreview}
            onChange={handleChange1}
          >

            {uploadedImageUrl ? (
              <img src={uploadedImageUrl} alt="Uploaded Image" style={{ width: '100%' }} />
            ) : (
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>点击上传</div>
              </div>
            )}
          </Upload>
        </Form.Item>


        <Form.Item label="主标题" name="fileName" rules={[{ required: true, message: '请输入主标题' }]}>
          <Input placeholder="请输入主标题" /> 
        </Form.Item>
        <Form.Item label="副标题" name="title" rules={[{ required: true, message: '请输入副标题' }]}>
          <Input placeholder="请输入副标题" /> 
        </Form.Item>
        <Form.Item label="原价" name="price" rules={[{ required: true, message: '请输入原价' }]}>
          <Input placeholder="请输入原价"  /> 
        </Form.Item>
        <Form.Item label="现价" name="oriPrice" rules={[{ required: true, message: '请输入现价' }]}>
          <Input placeholder="请输入现价"  /> 
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
